English
383. Ransom Note
Problem Statement
Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote.
Example 1:
Input: ransomNote = "a", magazine = "b"
Output: false
Example 2:
Input: ransomNote = "aa", magazine = "ab"
Output: false
Example 3:
Input: ransomNote = "aa", magazine = "aab"
Output: true
Constraints:
1 <= ransomNote.length, magazine.length <= 105ransomNoteandmagazineconsist of lowercase English letters.
Solution:
rs
impl Solution {
pub fn can_construct(ransom_note: String, magazine: String) -> bool {
// Convert the magazine string to a vector of characters
let mut magazine = magazine.chars().collect::<Vec<char>>();
// Iterate over the ransom note string
for c in ransom_note.chars() {
// If the magazine contains the character, remove it
// Otherwise, return false
// position() returns the index of the first element that matches the closure
// else returns None
if let Some(i) = magazine.iter().position(|&x| x == c) {
magazine.remove(i);
} else {
return false;
}
}
true
}
}
go
package main
func canConstruct(ransomNote string, magazine string) bool {
if len(ransomNote) > len(magazine) {
return false
}
// make a map of the magazine
mag := make(map[rune]int)
// count the number of each character in the magazine
for _, c := range magazine {
mag[c]++
}
// check if the ransom note can be made from the magazine
for _, c := range ransomNote {
if mag[c] == 0 {
return false
}
mag[c]--
}
// // make a vector of the magazine
// magVec := make([]int, 26)
// for _, c := range magazine {
// magVec[c-'a']++
// }
// // check if ransomNote can be constructed from magazine
// for _, c := range ransomNote {
// if magVec[c-'a'] == 0 {
// return false
// }
// magVec[c-'a']--
// }
return true
}
...